package com.example.wxtest.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;

//创建菜单
public class CreateMenu {

    //
    public void createMenu() throws UnsupportedEncodingException {
//        1.获取accessToken
        String assessToken = this.accessToken();
//        2.菜单json
        String json = "{\"button\":[{\"type\":\"view\",\"name\":\"首页\"," +
                "\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Configure.appId +
                "&redirect_uri=" + Base64Encode.enCode(Configure.pages[0]) +
                "&response_type=code&scope=snsapi_userinfo#wechat_redirect\"},{\"type\":\"view\",\"name\":\"测试首页\"," +
                "\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Configure.appId + "&redirect_uri=" +
                Base64Encode.enCode(Configure.pages[1]) +
                "&response_type=code&scope=snsapi_userinfo#wechat_redirect\"}],\"type\":\"view\",\"appid\":\"wxa89ffeadbc555bb1\"}";
//        3.发送请求
        System.out.println(this.accessToken());
        SignUtil.doPostToJson("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + this.accessToken(), json);

    }

    public String accessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Configure.appId + "&secret=" + Configure.appsecret;
        String accessTokenBody = cn.hutool.http.HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(accessTokenBody);
        String accessToken = null;
        try {
            accessToken = (String) jsonObject.get("access_token");
        } catch (Exception e) {
            System.out.println(e);
        }
        return accessToken;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        CreateMenu createMenu = new CreateMenu();
        createMenu.createMenu();
    }
}